package scene_widget

import (
	"fyne.io/fyne/v2"
	"fyne.io/fyne/v2/canvas"
	"fyne.io/fyne/v2/driver/desktop"
	"fyne.io/fyne/v2/theme"
	"fyne.io/fyne/v2/widget"
	"image/color"
)

// NewButton 自定义新建按钮组件
type NewButton struct {
	widget.BaseWidget
	currentIcon      *canvas.Image
	buttonBackground *canvas.Rectangle
	onTapped         func()
}

// 确保NewButton实现必要的接口
var _ desktop.Hoverable = (*NewButton)(nil)
var _ fyne.Tappable = (*NewButton)(nil)

// NewElementButton 创建一个新的新建按钮
func NewElementButton() *NewButton {
	btn := &NewButton{}
	btn.ExtendBaseWidget(btn)
	return btn
}

// CreateRenderer 实现fyne.Widget接口
func (btn *NewButton) CreateRenderer() fyne.WidgetRenderer {
	// 使用搜索图标
	searchIcon := theme.ContentAddIcon()

	btn.currentIcon = canvas.NewImageFromResource(searchIcon)
	btn.currentIcon.FillMode = canvas.ImageFillContain

	btn.buttonBackground = canvas.NewRectangle(color.White)
	btn.buttonBackground.CornerRadius = 4
	btn.buttonBackground.StrokeColor = color.Gray{100}
	btn.buttonBackground.StrokeWidth = 1

	return &newButtonRenderer{
		button: btn,
		objects: []fyne.CanvasObject{
			btn.buttonBackground,
			btn.currentIcon,
		},
	}
}

// newButtonRenderer 新建按钮渲染器
type newButtonRenderer struct {
	button  *NewButton
	objects []fyne.CanvasObject
}

// Layout 布局
func (r *newButtonRenderer) Layout(size fyne.Size) {
	r.button.buttonBackground.Resize(size)
	// 根据按钮大小动态调整图标大小，确保图标不会超出按钮范围
	iconSize := fyne.NewSize(size.Width*0.8, size.Height*0.8) // 图标大小为按钮的80%
	r.button.currentIcon.Resize(iconSize)
	// 居中图标
	iconPos := fyne.NewPos(
		(size.Width-iconSize.Width)/2,
		(size.Height-iconSize.Height)/2,
	)
	r.button.currentIcon.Move(iconPos)
}

// MinSize 返回按钮的最小尺寸
func (r *newButtonRenderer) MinSize() fyne.Size {
	return fyne.NewSize(16, 16) // 保持与RunButton一致的最小尺寸
}

// Refresh 刷新
func (r *newButtonRenderer) Refresh() {
	// 新建按钮使用搜索图标，背景色为蓝色
	r.button.currentIcon.Resource = theme.SearchIcon()
	r.button.buttonBackground.FillColor = color.RGBA{0, 123, 255, 100} // 蓝色背景

	for _, obj := range r.objects {
		obj.Refresh()
	}
}

// Objects 对象列表
func (r *newButtonRenderer) Objects() []fyne.CanvasObject {
	return r.objects
}

// Destroy 销毁
func (r *newButtonRenderer) Destroy() {}

// Tapped 点击事件
func (btn *NewButton) Tapped(_ *fyne.PointEvent) {
	// 触发点击回调
	if btn.onTapped != nil {
		btn.onTapped()
	}
}

// MouseIn 鼠标进入
func (btn *NewButton) MouseIn(_ *desktop.MouseEvent) {
	// 不改变按钮外观，保持原样
}

// MouseOut 鼠标离开
func (btn *NewButton) MouseOut() {
	// 不改变按钮外观，保持原样
}

// MouseMoved 鼠标移动
func (btn *NewButton) MouseMoved(_ *desktop.MouseEvent) {}

// SetOnTapped 设置点击回调
func (btn *NewButton) SetOnTapped(fn func()) {
	btn.onTapped = fn
}
